<?php

/**
 * Array conversion 
 * 
 * @package  Arrow
 * @license  GNU GPL
 * @author   Artur Kmera <artur.kmera@arrowplatform.org> 
 */

class JSONRemoteResponseHandler implements IRemoteResponseHandler {

	/**
	 * Singleton
	 *
	 * @var object
	 */
	private static $selfInstance = false;

	/**
	 * Return object instance
	 *
	 * @return Singleton
	 * @access public
	 * @static
	 */
	public static function getDefault() {
		if (self :: $selfInstance == false) {
			self :: $selfInstance = new JSONRemoteResponseHandler();
		}
		return self :: $selfInstance;
	}

	/**
	 * Konstruktor. Tworzy nowy dokument DOM.
	 * 
	 * @return void
	 */
	private function __construct() {

	}

	/**
	 * Zmienia tablecę w dokument DOM
	 * 
	 * @param array $array Zmieniana tablica.
	 * @param DOMNode $parentNode Węzeł - rodzic - dla rekursywnego wywołania. 
	 */ 
	private function parse($array) {
		
		if( is_object($array) && (in_array("IArrowSerializable", class_implements($array)) || $array instanceof Persistent ) ){
			$array = $array->serialize();
		}elseif(!is_array($array)){
			return $array;
		}
		
		
		foreach( $array as $key => $child )
			$array[$key] = $this->parse($child);
		
		return $array;
		
		

	}

	/**
	 * Zmienia tablicę w XML
	 * 
	 * @param array $array Tablica do zmiany.
	 */
	public function getResponse($array) {
		if(is_array($array) || is_object($array)){
			$array = $this->parse($array);
		}else{
			$array = array( "singleResponse" => $array);
		}
		return json_encode($array);
	}

	/**
	 * Ustawia nagłówki pzeglądarki do odczytu dokumentu xml.
	 * 
	 * @return void
	 */
	function setHeaders() {

		header("Content-type: text/x-json");
		header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
		header("Last-Modified: ".gmdate("D, d M Y H:i:s")." GMT");
		header("Cache-Control: no-store, no-cache, must-revalidate");
		header("Cache-Control: post-check=0, pre-check=0", false);
		header("Pragma: no-cache");

	}
}
?>